from annoying.decorators import render_to
from django.shortcuts import get_object_or_404, redirect
from django.http import Http404
from datetime import datetime
from django.http import HttpResponse
from django.utils import simplejson

from core.models import Discussion, Message, Event, User
from core.forms import DiscussionForm, MessageForm
from core.lib import is_user_authenticated


@render_to('event/discussion.html')
def discussion(request, id):
    discuss = get_object_or_404(Discussion, id=id)
    event = get_object_or_404(Event, id=discuss.event.id)
    message_form = False
    if is_user_authenticated(request) and \
        User.objects.get(id=request.session['user_id']) in event.participants.all():
        message_form = MessageForm()
    return {'messages': Message.objects.filter(discussion=discuss),
            'message_form': message_form, 'discussion': discuss}    


def add_message(request, id):
    if request.is_ajax():
        discuss = get_object_or_404(Discussion, id=id)
        user = User.objects.get(id=request.session['user_id'])
        form = MessageForm()
        message = form.save(commit=False)
        message.text = request.POST['text']
        message.author = user
        message.addressee = user
        message.datetime = datetime.now()
        message.discussion = discuss
        message.save()
        return HttpResponse(simplejson.dumps({'success': True}), mimetype='application/json')
    else:
        return HttpResponse(simplejson.dumps({'success': False}), mimetype='application/json')

   
@render_to('event/create_discussion.html') 
def create_discussion(request, id):
    event = get_object_or_404(Event, id=id)
    user = User.objects.get(id=request.session['user_id'])
    if user not in event.participants.all():
        raise Http404()
    if request.method == 'POST':
        form = DiscussionForm(request.POST)
        if form.is_valid():
            discuss = form.save(commit=False)
            discuss.event = event
            discuss.save()
            return redirect(discussion, discuss.id)
    else:
        form = DiscussionForm()
    return {'discussion_form': form}